package com.zhuj.server;

import com.zhuj.handler.RpcChannelInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by Administrator on 2018/1/3.
 */
public class NrpcServer {

    private static final Logger LOG = LoggerFactory.getLogger(NrpcServer.class);

    private EventLoopGroup bossGroup;

    private EventLoopGroup workGroup;

    private ServerBootstrap bootstrap;

    private void server(){
        bossGroup = new NioEventLoopGroup();
        workGroup = new NioEventLoopGroup();
        bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup,workGroup)
                 .option(ChannelOption.SO_BACKLOG,1024)
                 .channel(NioServerSocketChannel.class)
                 .childHandler(new RpcChannelInitializer());
    }

    public void start(int port){
        server();
        try {
            ChannelFuture future = bootstrap.bind(port).sync();
            LOG.info("nrpc server start on : "+port);
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            LOG.info("nrpc server closed");
        }
    }

    public void stop(){
        bossGroup.shutdownGracefully();
        workGroup.shutdownGracefully();
    }

}
